import userApi from '@/api/system/user'
import { parseTime } from '@/utils/index'
import roleApi from '@/api/system/role'

export default {
  name:'user',
  data() {
    return {
      roleDialog: {
        visible: false,
        roles: [],
        roleTree: [],
        checkedRoleKeys: [],
        defaultProps: {
          id: 'id',
          label: 'name',
          children: 'children'
        }
      },
      statusList:[
        {label:'启用',value:'0'},
        {label:'冻结',value:'1'}
      ],
      formVisible: false,
      formTitle: '添加用户',
      deptTree: {
        data: [],
      },
      isAdd: true,
      form: {
        id: '',
        username: '',
        nickname: '',
        sex: 1,
        email: '',
        password: '',
        rePassword: '',
        statusBool: true
      },
      rules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      listQuery: {
        current: 1,
        size: 20,
        criteria:{
          username: '',
          nickname: '',
          phone:'',
          status:'',
          sex:''
        }
      },
      total: 0,
      list: null,
      listLoading: true,
      selRow: {}
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      userApi.getList(this.listQuery).then(response => {
        this.list = response.data.records
        this.listLoading = false
        this.total = response.data.total
      })
    },
    formatDate(originVal) {
        const dt = new Date(originVal);
        const y = dt.getFullYear();
        const m = (dt.getMonth() + 1 + "").padStart(2, "0");
        const d = (dt.getDate() + "").padStart(2, "0");
        const hh = (dt.getHours() + "").padStart(2, "0");
        const mm = (dt.getMinutes() + "").padStart(2, "0");
        const ss = (dt.getSeconds() + "").padStart(2, "0");
        return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    search() {
      this.listQuery.current = 1
      this.fetchData()
    },
    reset() {
      this.listQuery.criteria.username = ''
      this.listQuery.criteria.nickname = ''
      this.listQuery.current = 1
      this.listQuery.criteria.status ='1'
      this.listQuery.criteria.phone=''
      this.listQuery.criteria.sex=''
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.current = 1
      this.fetchData()
    },
    handleClose() {

    },
    fetchNext() {
      this.listQuery.current = this.listQuery.current + 1
      this.fetchData()
    },
    fetchPrev() {
      this.listQuery.current = this.listQuery.current - 1
      this.fetchData()
    },
    fetchPage(page) {
      this.listQuery.current = page
      this.fetchData()
    },
    changeSize(limit) {
      this.listQuery.size = limit
      this.fetchData()
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selRow = currentRow
    },
    resetForm() {
      this.form = {
        id: '',
        username: '',
        nickname: '',
        sex: 1,
        password: '',
        rePassword: '',
        statusBool: true
      }
    },
    add() {
      this.resetForm()
      this.formTitle = '添加用户'
      this.formVisible = true
      this.isAdd = true
    },
    changeUserStatus(record){
      userApi.changeStatus(record.id).then(response => {
        this.$message({
          message: '提交成功',
          type: 'success'
        })
        this.fetchData()
      })
    },
    validPasswd() {
      if (!this.isAdd) {
        return true
      }

      if (this.form.password !== this.form.rePassword) {
        this.$message({
          message: '前后密码不一致',
          type: 'error'
        })
        return false
      }
      if (this.form.password === '' || this.form.rePassword === '') {
        this.$message({
          message: '密码不能为空',
          type: 'error'
        })
        return false
      }
      return true
    },
    saveUser() {
      let self = this
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.validPasswd()) {
            let form = self.form
            if (form.statusBool === true) {
              //启用
              form.status = 0
            } else {
              //冻结
              form.status = 1
            }
            userApi.saveUser(form).then(response => {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.fetchData()
              this.formVisible = false
            })
          }
        } else {
          return false
        }
      })
    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true
      }
      this.$message({
        message: '请选中操作项',
        type: 'warning'
      })
      return false
    },
    editItem(record){
      this.selRow= Object.assign({},record);
      
      this.edit()
    },
    edit() {
      if (this.checkSel()) {
        this.isAdd = false
        let form = Object.assign({}, this.selRow);
        form.statusBool = form.status == '0'
        form.sex = form.sex == '1'?1:0
        this.form = form
        this.formTitle = '修改用户'
        this.formVisible = true
      }
    },
    removeItem(record){
      this.selRow = record
      this.remove()
    },
    remove() {
      if (this.checkSel()) {
        let id = this.selRow.id

        this.$confirm('确定删除该记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          userApi.remove(id).then(response => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.fetchData()
          })
        }).catch(() => {
        })
      }
    },

    resetPwd() {
      if (this.checkSel()) {
        var id = this.selRow.id
        this.$confirm('密码将重置为111111?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          userApi.resetPassword(id).then(response => {
            this.$message({
              message: '重置密码成功',
              type: 'success'
            })
          }).catch(err => {
            this.$notify.error({
              title: '错误',
              message: err,
            })
          })
        }).catch(() => {
        })
      }
    },
    chooseDept(data,node){
      this.listQuery.deptid = data.id
      this.search()
    },
    openRoleItem(record){
      this.selRow = record
      this.openRole()
    },
    openRole() {
      if (this.checkSel()) {
        roleApi.roleTreeListByIdUser(this.selRow.id).then(response => {
          this.roleDialog.roles = response.data.treeData
          this.roleDialog.checkedRoleKeys = response.data.checkedIds
          this.roleDialog.visible = true
        })
      }
    },
    setRole() {
      var checkedRoleKeys = this.$refs.roleTree.getCheckedKeys()
      var roleIds = []
      for (var index in checkedRoleKeys) {
        roleIds.push( checkedRoleKeys[index] )
      }
      var data = {
        userId: this.selRow.id,
        roleIds: roleIds
      }
      userApi.setRole(data).then(response => {
        this.roleDialog.visible = false
        this.fetchData()
        this.$message({
          message: '提交成功',
          type: 'success'
        })
      })
    }

  }
}
